package woaini.fenger.core.bot.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ReflectUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import woaini.fenger.core.base.boot.ApplicationStartupCompleted;
import woaini.fenger.core.bot.base.Bot;
import woaini.fenger.core.bot.config.BotConfig;
import woaini.fenger.core.bot.manager.key.BotKey;
import woaini.fenger.core.config.WindConfig;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * BOT管理器 所有已经运行的bot在这里进行存储和获取
 *
 * @see woaini.fenger.core.bot.manager.BotManager
 * @author yefeng {@code @Date} 2023-05-16 16:50:39
 */
@Component
@Slf4j
@EnableConfigurationProperties(WindConfig.class)
@AllArgsConstructor
public class BotManager implements ApplicationStartupCompleted {

    private final WindConfig windConfig;
    private static final Map<BotKey, Bot> BOT_CACHE = new HashMap<>(10);

    public void register(Bot bot) {
        log.info("注册bot:{}", bot.getKey());
        BOT_CACHE.put(bot.getKey(), bot);
        //获取是否自动登录
        Boolean autoLogin = bot.getBotConfig().getAutoLogin();
        if (autoLogin){
            log.info("自动登录bot:{}", bot.getKey());
            bot.conncet();
        }
    }
    public Bot getBot(BotKey botKey) {
        return BOT_CACHE.get(botKey);
    }
    public Collection<Bot> getBots() {
        return BOT_CACHE.values();
    }
    public void remove(BotKey botKey) {
        log.info("移除bot:{}", botKey);
        BOT_CACHE.remove(botKey);
    }

    @Override
    public void onInit() {
        List<BotConfig> bots = windConfig.getBots();
        if (CollUtil.isEmpty(bots)){
            return;
        }
        for (BotConfig botConfig : bots) {
            Class<? extends BotConfig> configClass = botConfig.getBotConfigClass();
            Object config = ReflectUtil.newInstance(configClass);
            BeanUtil.copyProperties(botConfig, config);

            Class<?> aClass = botConfig.getBotClass();
            Object bot = ReflectUtil.newInstance(aClass, config);
            register((Bot) bot);
        }
    }
}
